package com.xmy.cultivate.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.Dict;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.service.IDictService;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
 * @author min
 * @since 2022-07-25
 */
@RestController
@RequestMapping("/api/dict")
@Scope("prototype")
public class DictController extends BaseController{

    @Autowired
    IDictService iDictService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IQuarterService iQuarterService;

    /**
     * 获取字典表 租金
     * @param type
     * @return
     */
    @GetMapping("/dictList")
    public Result dictList(@RequestParam(value = "type", defaultValue = "") String type){
        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("type",type);
        dictQueryWrapper.eq("status",1);
        //根据num排序
        dictQueryWrapper.orderByAsc("num");
        List<Dict> list = iDictService.list(dictQueryWrapper);
        return new Result(Code.OK,list,Code.GET_OK_MSG);
    }


    @GetMapping()
    public Result findAll(@RequestParam Map reMap){
        try{
            Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
            Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 10: Integer.valueOf((String)reMap.get("pageSize"));
            //StringUtils.isEmpty(reMap.get("pageNum"));
            IPage<Dict> iPage = new Page<>(pageNum,pageSize);
            String type = (String) reMap.get("type");
            QueryWrapper<Dict> dictQueryWrapper =  new QueryWrapper<>();
            dictQueryWrapper.eq(StringUtils.isNotBlank(type),"type",type);
            dictQueryWrapper.eq("deleted",0);
            dictQueryWrapper.orderByAsc("type","sort");

            iDictService.findAll(iPage,dictQueryWrapper);
            return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));

        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }
    @GetMapping("/findForTypes")
    public Result findForTypes(@RequestParam Map reMap){
        try{
            String type = (String) reMap.get("type");
            QueryWrapper<Dict> dictQueryWrapper =  new QueryWrapper<>();
            dictQueryWrapper.eq("deleted",0);
            dictQueryWrapper.eq(StringUtils.isNotBlank(type),"type",type);
            dictQueryWrapper.eq("status",1);
            List<Dict> dictList = iDictService.list(dictQueryWrapper);
            for (Dict dict:dictList){
                dict.setId(Long.parseLong(dict.getNum().toString()));
            }
            return new Result(Code.OK,new PageResult(dictList,(long)dictList.size(),1L));

        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }




    @GetMapping("/{id}")
    public Result findById(@PathVariable(value = "id") String id){
        try{
            Dict dict = iDictService.getById(id);
            //long ids =  idWorker.nextId();
            //System.out.println(ids);
            return new Result(Code.OK,dict);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }


    @PostMapping()
    public Result save(@RequestBody Dict dict){
        try{
            Integer maxNum = iDictService.getMaxNumForType(17);
            dict.setNum(maxNum);
            boolean rs = iDictService.save(dict);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @PostMapping("/saveForType")
    public Result saveForType(@RequestBody Dict dict){
        try{
            Integer maxNum = iDictService.getMaxNumForType(dict.getType());
            dict.setNum(maxNum);
            boolean rs = iDictService.save(dict);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id,@RequestBody Dict dict){
        try{
            //System.out.println(dict);
            boolean rs = iDictService.updateById(dict);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id){
        try{
            boolean rs =  iDictService.removeById(id);
            return new Result(rs?Code.OK:Code.ERROR);
        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    @GetMapping("/getQuarterList")
    public Result getQuarterList(@RequestParam Map reMap,Integer types[]){
        try{
            Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
            Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 1000: Integer.valueOf((String)reMap.get("pageSize"));
            //StringUtils.isEmpty(reMap.get("pageNum"));
            IPage<Dict> iPage = new Page<>(pageNum,pageSize);
            QueryWrapper<Dict> dictQueryWrapper =  new QueryWrapper<>();
            dictQueryWrapper.eq("deleted",0);

            if(types.length>0){
                dictQueryWrapper.in("type",types);
            }else {
                dictQueryWrapper.eq("type",19);
            }
            iDictService.page(iPage,dictQueryWrapper);
            Quarter quarter = iQuarterService.getNowQuarter();
            for(Dict dictInfo : iPage.getRecords()){
                if (dictInfo.getNum().equals(quarter.getNum())){
                    dictInfo.setIsCurrent(1);
                }else {
                    dictInfo.setIsCurrent(0);
                }
            }

            return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));

        }catch (Exception e){
            return new Result(Code.ERROR,e.getMessage());
        }
    }

    /**
     * 获取班级AB类型
     * @return
     */
    @GetMapping("/getGradeAb")
    public Result getGradeAb(@RequestParam("yearPart") Integer yearPart,
                             @RequestParam("quarterNum") Integer quarterNum
                             ){
        Quarter quarterInfo = iQuarterService.getQuarterForYearAndNum(yearPart,quarterNum);
        if (ObjectUtil.isNull(quarterInfo)){
            return new Result(Code.ERROR,"","年份学期不存在");
        }
        QueryWrapper<Dict> dictQueryWrapper =  new QueryWrapper<>();
        dictQueryWrapper.eq("type",34);
        dictQueryWrapper.eq("status",1);
        //学期
        if(quarterInfo.getType().equals(1)){
            dictQueryWrapper.eq("tag",0);
            dictQueryWrapper.orderByAsc("sort");

        }else {
            //假期
            if (quarterInfo.getNum().equals(1)){
                dictQueryWrapper.eq("name","A天");
            }
            dictQueryWrapper.eq("tag",1);
            dictQueryWrapper.orderByAsc("sort");
        }
        List<Dict> dictList = iDictService.list(dictQueryWrapper);
        return new Result(Code.OK,dictList,"");
    }

    @PostMapping("/saveExamNum")
    public Result saveExamNum(@RequestBody Dict dict) {
        Integer maxNumForType = iDictService.getMaxNumForType(42);
        dict.setNum(maxNumForType == 0 ? 100 : maxNumForType + 1);
        dict.setType(42);
        dict.setRemark("考试名称");
        iDictService.save(dict);
        return new Result(Code.SAVE_OK,null,Code.SAVE_OK_MSG);
    }

    @GetMapping("/getExamNumList")
    public Result getExamNumList() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", 42);
        queryWrapper.eq("deleted", 0);
        //根据num排序
        queryWrapper.orderByAsc("num");
        List<Dict> examNumList = iDictService.list(queryWrapper);
        return new Result(Code.OK, examNumList, Code.GET_OK_MSG);
    }
}
